package com.ruoyi.record.service.impl;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.basic.domain.BasicUser;
import com.ruoyi.basic.mapper.BasicUserMapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.record.mapper.RecordSalaryContentMapper;
import com.ruoyi.record.domain.RecordSalaryContent;
import com.ruoyi.record.service.IRecordSalaryContentService;
import com.ruoyi.common.core.text.Convert;

/**
 * 工资详情Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-02-12
 */
@Service
public class RecordSalaryContentServiceImpl extends ServiceImpl<RecordSalaryContentMapper, RecordSalaryContent> implements IRecordSalaryContentService
{
    @Autowired
    private BasicUserMapper basicUserMapper;

    /**
     * 查询工资详情
     * 
     * @param contentId 工资详情主键
     * @return 工资详情
     */
    @Override
    public RecordSalaryContent selectRecordSalaryContentByContentId(Long contentId)
    {
        return baseMapper.selectRecordSalaryContentByContentId(contentId);
    }

    /**
     * 查询工资详情列表
     * 
     * @param recordSalaryContent 工资详情
     * @return 工资详情
     */
    @Override
    public List<RecordSalaryContent> selectRecordSalaryContentList(RecordSalaryContent recordSalaryContent)
    {
        return baseMapper.selectRecordSalaryContentList(recordSalaryContent);
    }

    /**
     * 新增工资详情
     * 
     * @param recordSalaryContent 工资详情
     * @return 结果
     */
    @Override
    public int insertRecordSalaryContent(RecordSalaryContent recordSalaryContent)
    {
        recordSalaryContent.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insert(recordSalaryContent);
    }

    /**
     * 修改工资详情
     * 
     * @param recordSalaryContent 工资详情
     * @return 结果
     */
    @Override
    public int updateRecordSalaryContent(RecordSalaryContent recordSalaryContent)
    {
        recordSalaryContent.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateById(recordSalaryContent);
    }

    /**
     * 批量删除工资详情
     * 
     * @param contentIds 需要删除的工资详情主键
     * @return 结果
     */
    @Override
    public int deleteRecordSalaryContentByContentIds(String contentIds)
    {
        return baseMapper.deleteBatchIds(Arrays.asList(Convert.toLongArray(contentIds)));
    }

    /**
     * 删除工资详情信息
     * 
     * @param contentId 工资详情主键
     * @return 结果
     */
    @Override
    public int deleteRecordSalaryContentByContentId(Long contentId)
    {
        return baseMapper.deleteById(contentId);
    }

    /**
     * 导入招聘计划
     *
     * @param contentList 员工行政职务列表
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importContent(List<RecordSalaryContent> contentList, Long salaryId, String salaryType, boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(contentList) || contentList.size() == 0)
        {
            throw new ServiceException("导入员工行政职务数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        int row = 2;
        String REGEX_LOCALE_ENGLISH = "^[a-zA-Z]{3}\\s[a-zA-Z]{3}\\s\\d{2}\\s\\d{2}:\\d{2}:\\d{2}\\s[A-Z]{3}\\s\\d{4}$";
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (RecordSalaryContent content : contentList)
        {
            try
            {
                if(StringUtils.isEmpty(content.getIdCard())){
                    continue;
                }
                content.setSalaryId(salaryId);
                content.setSalaryType(salaryType);
                //验证用户是否存在
                BasicUser basicUser = basicUserMapper.selectOne(new LambdaQueryWrapper<BasicUser>().eq(BasicUser::getIdCard, content.getIdCard()));
                if(StringUtils.isNull(basicUser)) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、第 " + row + "行导入失败，员工 " + content.getUserName() + " 不存在");
                    continue;
                }
                content.setUserId(basicUser.getId());

                SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);

                if(StringUtils.isNotEmpty(content.getA32()) && content.getA32().matches(REGEX_LOCALE_ENGLISH)) {
                    Date a32 = dateFormat.parse(content.getA32());
                    content.setA32(DateUtils.parseDateToStr("yyyy-MM-dd", a32));
                }

                RecordSalaryContent info = baseMapper.selectOne(new LambdaQueryWrapper<RecordSalaryContent>()
                        .eq(RecordSalaryContent::getSalaryId, content.getSalaryId())
                        .eq(RecordSalaryContent::getUserId, content.getUserId()));
                if (StringUtils.isNull(info))
                {
                    content.setCreateBy(operName);
                    this.insertRecordSalaryContent(content);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、第" + row + " 行工资信息导入成功");
                }
                else if (isUpdateSupport)
                {
                    content.setContentId(info.getContentId());
                    content.setUpdateBy(operName);
                    this.updateRecordSalaryContent(content);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、第" + row + " 行工资信息更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + successNum + "、第：" + row + " 行工资信息已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、第" + row + " 行工资信息导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
            finally {
                row++;
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 校验工资记录
     *
     * @param recordSalaryContent 工资记录
     * @return 结果
     */
    @Override
    public boolean checkSalaryContent(RecordSalaryContent recordSalaryContent) {
        Long contentId = StringUtils.isNull(recordSalaryContent.getContentId()) ? -1L : recordSalaryContent.getContentId();
        LambdaQueryWrapper<RecordSalaryContent> queryWrapper = new LambdaQueryWrapper<RecordSalaryContent>().eq(RecordSalaryContent::getSalaryId, recordSalaryContent.getSalaryId());
        if(StringUtils.isNotNull(recordSalaryContent.getUserId())){
            queryWrapper.eq(RecordSalaryContent::getUserId, recordSalaryContent.getUserId());
        }
        RecordSalaryContent info = baseMapper.selectOne(queryWrapper.last("limit 1"));
        if (StringUtils.isNotNull(info) && info.getContentId().longValue() != contentId.longValue())
        {
            return false;
        }
        return true;
    }
}
